var deletedPictures = new Array(), initSuccess = false;
var goodname = $("#goodname"), goodcode = $("#goodcode"), goodspecs = $("#goodspecs"), meteringunit = $("#meteringunit"), goodprice = $("#goodprice"), manufacturer = $("#manufacturer"), gooddetail = $("#gooddetail");
var goodpicture = $("#goodpicture"), goodpictureId = $("#goodpictureId"), goodpictureImage = $("#goodpictureImage");
var imageContainer = $(".image-container");

$(function() {
	$("input[prop='fileInput']").change(onFileInputChanged);
	$("img[prop='fileViewer']").click(onFileViewerClick);
	$("i[prop='fileSelector']").click(onFileSelectorClick);
	
	if (__goodId) {
		mobileGlobal.sendRequest(__mobilectx + "/supplier/good/loadMgrGoodData.xhtml", {goodid : __goodId}, null, function(data, status) {
			if (data.status) {
				goodname.val(data.result.goodname);
				goodcode.val(data.result.goodcode);
				goodspecs.val(data.result.goodspecs);
				meteringunit.val(data.result.meteringunit);
				goodprice.val(data.result.goodprice);
				manufacturer.val(data.result.manufacturer);
				gooddetail.val(data.result.gooddetail);
				goodpictureId.val(data.result.coverpicture.pictureid);
				goodpictureImage.attr("src", data.result.coverpicture.picturepath);
				
				var rowid = 0;
				if (data.result.otherpictures && data.result.otherpictures.length > 0) {
					for (var i = 0; i < data.result.otherpictures.length; i ++) {
						var otherpicture = data.result.otherpictures[i];
						addNewPictureRow(i + 1, false, null, otherpicture.pictureid, otherpicture.picturepath);
					}
					rowid = data.result.otherpictures.length;
				}
				addNewPictureRow(rowid + 1);
				
				initSuccess = true;
				
				mobileGlobal.hideLoading();
			} else {
				mobileGlobal.hideLoading();
				mobileGlobal.failed("加载数据失败");
			}
		});
	} else {
		addNewPictureRow(1);
		initSuccess = true;
	}
});

//返回按钮点击事件
function onBackClick() {
	mobileGlobal.backword();
}

//保存按钮点击事件
function onSaveClick() {
	if (!initSuccess) {
		mobileGlobal.message("页面加载错误");
		return;
	}
	
	var formData = new FormData();
	
	//基本信息
	if (__goodId) formData.append("goodid", __goodId);
	formData.append("goodname", goodname.val());
	formData.append("goodcode", goodcode.val());
	formData.append("goodspecs", goodspecs.val());
	formData.append("meteringunit", meteringunit.val());
	formData.append("goodprice", goodprice.val());
	formData.append("manufacturer", manufacturer.val());
	formData.append("gooddetail", gooddetail.val());
	
	//封面图片
	if (goodpicture[0].files[0]) formData.append("goodpicture", goodpicture[0].files[0]);
	
	//更多图片
	var pictureRows = $("div[prop='pictureRow']");
	for (var i = 0; i < pictureRows.length; i ++) {
		var file = $(pictureRows[i]).find("input[type='file']");
		if (file[0].files[0]) formData.append("goodpictures", file[0].files[0]);
	}
	
	//删除图片
	formData.append("deletedpictures", deletedPictures.join(","));
	
	if (!formData.get("goodname")) {
		mobileGlobal.message("商品名称必须填写");
		return;
	}
	if (!formData.get("goodcode")) {
		mobileGlobal.message("商品编码必须填写");
		return;
	}
	if (!formData.get("goodspecs")) {
		mobileGlobal.message("商品规格必须填写");
		return;
	}
	if (!formData.get("meteringunit")) {
		mobileGlobal.message("计量单位必须填写");
		return;
	}
	if (formData.get("goodprice")) {
		if (!/^(0|([1-9]\d*))(\.\d{1,2})?$/.test(formData.get("goodprice"))) {
			mobileGlobal.message("商品价格必须为有效的数字");
			return;
		}
	} else formData.set("goodprice", "0");
	if (!formData.get("manufacturer")) {
		mobileGlobal.message("生产厂家必须填写");
		return;
	}
	if (!formData.get("goodpicture") && !goodpictureId.val()) {
		mobileGlobal.message("封面图片必须上传");
		return;
	}
	
	mobileGlobal.loading("正在提交数据，请稍后...");
	
	$.ajax({
		url : __mobilectx + "/supplier/good/updateGood.xhtml", 
		data : formData, 
		contentType : false, 
		processData : false, 
		success : function(data, status) {
			mobileGlobal.hideLoading();
			if (data.status) {
				mobileGlobal.openMessageDialog("保存商品成功！", function() {
					mobileGlobal.closeMessageDialog();
					mobileGlobal.backword();
				});
			} else {
				mobileGlobal.openMessageDialog(data.result, function() {
					mobileGlobal.closeMessageDialog();
				});
			}
		}, 
		error : function(xhr, msg, e) {
			mobileGlobal.hideLoading();
			mobileGlobal.openMessageDialog("网络请求错误！", function() {
				mobileGlobal.closeMessageDialog();
			});
		}
	});
}

//文件输入框变化事件
function onFileInputChanged(e) {
	var file = e.currentTarget.files[0];
	if (!/^.+\.(jpg)|(jpeg)|(png)$/.test(file.name)) {
		mobileGlobal.message("请选择图片文件");
		return;
	}
	
	var rowid = $(e.currentTarget).parent().attr("rowid");
	$("#goodpictureImage" + rowid).attr("src", window.URL.createObjectURL(file));
}

//文件浏览器点击事件
function onFileViewerClick() {
	imageContainer.find("img").attr("src", $(this).attr("src"));
	imageContainer.fadeIn(200);
}

//文件选择框点击事件
function onFileSelectorClick() {
	var rowid = $(this).parent().attr("rowid"), $gpid = $("#goodpictureId" + rowid), gpid = $gpid.val();
	if (gpid) {
		mobileGlobal.openConfirmDialog("确定要替换原有图片？", function() {
			mobileGlobal.closeConfirmDialog();
			
			$gpid.val("");
			deletedPictures.push(gpid);
			$("#goodpicture" + rowid).click();
		});
	} else $("#goodpicture" + rowid).click();
}

//操作按钮点击事件
function onOperatorClick(obj) {
	var operator = $(obj);
	
	if (operator.hasClass("fa-plus-square")) {
		operator.removeClass("fa-plus-square").addClass("fa-minus-square");
		
		var parent = operator.parent(), rowid = parseInt(parent.attr("rowid")) + 1;
		addNewPictureRow(rowid, true, parent);
	} else {
		mobileGlobal.openConfirmDialog("确定要删除商品图片？", function() {
			mobileGlobal.closeConfirmDialog();
			
			var parent = operator.parent(), gpid = $("#goodpictureId" + parent.attr("rowid")).val();
			if (gpid) deletedPictures.push(gpid);
			parent.parent().remove();
		});
	}
}

//添加新图片行
function addNewPictureRow(rowid, scroll, before, value, src) {
	var html = "<div class='row picture'><div prop='pictureRow' rowid='" + rowid + "'>" + 
				"<input id='goodpicture" + rowid + "' class='file' type='file' prop='fileInput'/>" + 
				"<input id='goodpictureId" + rowid + "' type='hidden'/>" + 
				"<img id='goodpictureImage" + rowid + "' class='image' prop='fileViewer' src='" + __ctx + "/static/image/mobile/noimg.png'/>" + 
				"<i class='fa fa-folder-open-o' prop='fileSelector'></i>" + 
				"<i class='fa fa-plus-square' onclick='onOperatorClick(this);'></i>" + 
			   "</div></div>";
	var append = $(html);
	append.find("input[prop='fileInput']").change(onFileInputChanged);
	append.find("img[prop='fileViewer']").click(onFileViewerClick);
	append.find("i[prop='fileSelector']").click(onFileSelectorClick);
	if (value) {
		append.find("input[type='hidden']").val(value);
		append.find("i.fa-plus-square").removeClass("fa-plus-square").addClass("fa-minus-square");
	}
	if (src) append.find("img[prop='fileViewer']").attr("src", src);
	
	if (before) before.parent().after(append);
	else $(".weui-cells_input").append(append);
	
	if (scroll) {
		var contentHeight = $(".weui-cells_input").get(0).scrollHeight;
		$(".weui-cells_input").get(0).scrollTop = contentHeight;
	}
}

//关闭图片容器
function closeImageContainer() {
	imageContainer.fadeOut(200);
}